package com.acme.service.email;

import com.acme.domain.email.Email;
import com.acme.domain.email.Queue;
import com.acme.domain.email.impl.QueueImpl;

public class EmailService implements Runnable {
	private Queue queue = new QueueImpl();
	private Thread t;
	private static EmailService instance = new EmailService();

	public EmailService() {
		t = new Thread(this);
		t.start();

	}

	public static EmailService getEmailService() {
		return instance;
	}

	public void sendNotificationEmail(Email email) {
		if (!(queue.isQueueClosed())) {
			queue.addEmail(email);
		}
	}

	@Override
	public void run() {
		Email emailToSent;
		while (true) {
			emailToSent = queue.getEmail();
			if (emailToSent != null) {
				System.out.println(emailToSent);
			}
			if (queue.getReturnFlag()) {
				return;
			}
		}
	}

	public void close() {
		synchronized (queue) {
			queue.setQueueClosed(true);
			if (!(queue.isEmpty())) {
				try {
					queue.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
			t.interrupt();
			System.out.println("OK");
		}
	}
}
